<?php

class LoginController extends Controller
{
	/**
	 * Declares class-based actions.
	 */
	public function actions()
	{
		return array(
			// captcha action renders the CAPTCHA image displayed on the contact page
			'captcha'=>array(
				'class'=>'CCaptchaAction',
				'backColor'=>0xFFFFFF,
			),
			// page action renders "static" pages stored under 'protected/views/site/pages'
			// They can be accessed via: index.php?r=site/page&view=FileName
			'page'=>array(
				'class'=>'CViewAction',
			),
		);
	}

	/**
	 * This is the default 'index' action that is invoked
	 * when an action is not explicitly requested by users.
	 */
	public function actionIndex()
	{
        $section = "login";
        $title = Yii::t('login','_LB_LOGIN');
        $data = array();
        $data['title'] = $title;
        
        $request = Yii::app()->request;
        
        $login = new UserComponent();
        
        $return_link = '';
        if (!isset($_POST["login"])) {
            $_SERVER['REQUEST_URI'] = urldecode($_SERVER['REQUEST_URI']);
            $pos = strpos($_SERVER['REQUEST_URI'],'=');
            $return_link = substr($_SERVER['REQUEST_URI'],$pos+1);
            $data['return_link'] = $return_link;
            $this->render('index',$data);
        }
        else {
            if ((isset($_POST['login']) && !$_POST['login']))
            {
                $errors[] = Yii::t('login','_MSG_EMAIL_NOT_EMPTY');
                $data["message_error"] = $errors;
                $data["login"] = $request->getPost('login');
                $this->render('index',$data);
            } else if ((isset($_POST['pwd']) && !$_POST['pwd']))
            {
                $errors[] = Yii::t('login','_MSG_PASSWORD_NOT_EMPTY');
                $data["message_error"] = $errors;
                $data["login"] = $request->getPost('login');
                $this->render('index',$data);
            } else if (isset($_POST['login']) && $login->isDeactivated($request->getPost('login')))
            {
                // check if user login is deactivated or not
                $errors[] = Yii::t('login','_LB_ACCOUNT_DEACTIVATED');
                $data["message_error"] = $errors;
                $data["login"] = $request->getPost('login');
                $this->render('index',$data);
            } else {
                //check user login
                $acces = null;

                if (isset($_POST["login"]) && isset($_POST["pwd"]))
                {
                    // free all SESSION variables
                    //Yii::app()->request->setBaseUrl($section);
                            
                    // check and use SHA1 to encode password
                    $acces = $login->connecter_utilisateur($_POST["login"], $_POST["pwd"]);
                }

                if ($acces <> NULL)
                {

                    $login->updateUser($acces['id']);

                    Yii::app()->session["user_id"] = $acces['id'];
                    Yii::app()->session["user_name"] = $acces['first_name'].' '.$acces['last_name'];
                    Yii::app()->session["group_id"] = $acces['group_id'];
                    if ($acces['group_id'] != ADMIN && $acces['group_id'] != EDITOR)
                    {
                        if ( isset($acces['id']))
                        {
                            $errors[] = Yii::t('login','_MSG_NOT_GRANTED');
                        }
                        else
                        {
                            $login->increaseLoginAttempts($request->getPost('login'));
                            if ($login->isDeactivated($request->getPost('login')))
                            {
                                $errors[] = Yii::t('login','_MSG_ACCOUNT_DEACTIVATED');
                            }
                            else
                            {
                                $errors[] = Yii::t('login','_MSG_INVALID_LOGIN_OR_PASSWORD');
                            }
                        }

                        $data["message_error"] = $errors;
                        $data["login"] = $request->getPost("login");

                        $this->render('index',$data);
                        exit();
                    }

                    //serialize current user

                    Yii::app()->session['user_serialize'] = serialize($acces);

                    $login->resetLoginAttempts($acces['email']);
                    if( $return_link == '')
                    {
                        $this->redirect(Yii::app()->baseUrl."/user/");
                    }
                    else
                    {
                        $this->redirect(HTTP.'://' . $_SERVER['HTTP_HOST'].$return_link);
                    }
                }
                else
                {
                    if (isset($_POST["login"]))
                    {
                         if ( isset($acces))
                        {
                            $errors[] = Yii::t('login','_MSG_NOT_GRANTED');
                        }
                        else
                        {
                            $login->increaseLoginAttempts($request->getPost('login'));
                            if ($login->isDeactivated($request->getPost('login')))
                            {
                                $errors[] = Yii::t('login','_LB_ACCOUNT_DEACTIVATED');
                            }
                            else
                            {
                                $errors[] = Yii::t('login','_LB_INVALID_LOGIN_OR_PASSWORD');
                            }
                        }

                        $data["message_error"] = $errors;
                        $data["login"] = $request->getPost("login");
                    }                       
                    $this->render('index',$data);
                }

            }
        }
		// renders the view file 'protected/views/site/index.php'
		// using the default layout 'protected/views/layouts/main.php'
		//$this->render('index',$data);
	}

	/**
	 * This is the action to handle external exceptions.
	 */
	public function actionError()
	{
	    if($error=Yii::app()->errorHandler->error)
	    {
	    	if(Yii::app()->request->isAjaxRequest)
	    		echo $error['message'];
	    	else
	        	$this->render('error', $error);
	    }
	}

	/**
	 * Displays the login page
	 */
	public function actionLogin()
	{
        
		$model=new LoginForm;

		// if it is ajax validation request
		if(isset($_POST['ajax']) && $_POST['ajax']==='login-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}

		// collect user input data
		if(isset($_POST['LoginForm']))
		{
			$model->attributes=$_POST['LoginForm'];
			// validate user input and redirect to the previous page if valid
			if($model->validate() && $model->login())
				$this->redirect(Yii::app()->user->returnUrl);
		}
		// display the login form
		$this->render('login',array('model'=>$model));
	}

	/**
	 * Logs out the current user and redirect to homepage.
	 */
	public function actionLogout()
	{
		Yii::app()->session->clear();
        Yii::app()->session->destroy();
		$this->redirect(Yii::app()->homeUrl);
	}
}